package srv

import (
	"fmt"
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"

	"github.com/spf13/viper"
)

// User 用户管理
type User struct {
	UserBll       *bll.User       `inject:""`
	UserTypeBll   *bll.UserType   `inject:""`
	LoginBll      *bll.Login      `inject:""`
	MenuBll       *bll.Menu       `inject:""`
	EnterpriseBll *bll.Enterprise `inject:""`
}

// Create 创建用户
func (a *User) Create(ctx *context.Context) error {
	ctx.WriteOperateLog("User.Create", "创建用户")

	var reqData schema.User
	if err := ctx.ParseJSON(&reqData); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	err := a.UserBll.Create(&reqData)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess("ok")
}

// Get 获取用户信息
func (a *User) Get(ctx *context.Context) error {
	item, err := a.UserBll.Get(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	} else if item == nil {
		return ctx.ResErrInternalServer(fmt.Errorf("无效的用户"))
	}

	data := map[string]interface{}{
		"user_id":       item.RecordID,
		"nickname":      item.Nickname,
		"real_name":     item.RealName,
		"enterprise_id": item.EnterpriseID,
		"user_type":     item.UserType,
		"gender":        item.Gender,
		"photo":         item.Photo,
		"post":          item.Post,
		"auth_status":   item.AuthStatus,
	}

	if item.EnterpriseID != "" {
		eitem, err := a.EnterpriseBll.Get(item.EnterpriseID)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		} else if item != nil {
			data["enterprise_name"] = eitem.Name
		}
	}

	if item.UserType != "" {
		typeItem, err := a.UserTypeBll.GetByCode(item.UserType)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		} else if typeItem != nil {
			data["user_type_name"] = typeItem.Name
		}
	}

	authUser, err := a.UserBll.GetAuthUser(item.RecordID)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	data["tel"] = authUser.Tel

	setting, err := a.UserBll.GetSetting(item.RecordID)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	data["settings"] = setting

	return ctx.ResSuccess(data)
}

// QuerySystemMenu 查询系统菜单
func (a *User) QuerySystemMenu(ctx *context.Context) error {
	items, err := a.LoginBll.QuerySystemMenuByUserType(ctx.Query("user_type"), ctx.Query("code"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(items)
}

// QueryCommonFunction 查询常用功能项
func (a *User) QueryCommonFunction(ctx *context.Context) error {
	items, err := a.UserBll.QueryCommonFunction(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	if len(items) == 0 {
		items = viper.GetStringSlice("default_common_function")
	}

	menus, err := a.MenuBll.QueryByIDs(items)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	var data []map[string]interface{}
	for _, item := range items {
		for _, menu := range menus {
			if item == menu.RecordID {
				data = append(data, map[string]interface{}{
					"record_id": menu.RecordID,
					"name":      menu.Name,
					"code":      menu.Code,
					"icon":      menu.Icon,
					"router":    menu.Router,
				})
				break
			}
		}
	}

	return ctx.ResSuccess(data)
}

// AppInitLogin 初始化移动端登录
func (a *User) AppInitLogin(ctx *context.Context) error {
	var reqData schema.LoginHistory
	if err := ctx.ParseJSON(&reqData); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	err := a.UserBll.CreateLoginHistory(&reqData)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess("ok")
}

// WriteOff 用户注销
func (a *User) WriteOff(ctx *context.Context) error {
	ctx.WriteOperateLog("Users.WriteOff", "用户注销")
	err := a.UserBll.WriteOff(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess("ok")
}

// QueryUserByName 根据名称查询用户
func (a *User) QueryUserByName(ctx *context.Context) error {
	var (
		name string
		err  error
		data []*schema.UserShow
	)
	name = ctx.Param("name")
	data, err = a.UserBll.Search(name, 20)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(data)
}
